package com.system.ad.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.system.ad.dump.DConstant;
import com.system.ad.entity.*;
import com.system.ad.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("ad/export")
public class ExportController {

    @Autowired
    private CreativeService creativeService;
    @Autowired
    private CreativeUnitService creativeUnitService;
    @Autowired
    private PlanService planService;
    @Autowired
    private UnitService unitService;
    @Autowired
    private UnitDistrictService unitDistrictService;
    @Autowired
    private UnitItService unitItService;
    @Autowired
    private UnitKeywordService unitKeywordService;

    @RequestMapping("/tableList")
    public void tableList() {
        List<CreativeEntity> creativeList = creativeService.list();
        List<CreativeUnitEntity> creativeUnitList = creativeUnitService.list();
        List<PlanEntity> planList = planService.list();
        List<UnitEntity> unitList = unitService.list();
        List<UnitDistrictEntity> districtList = unitDistrictService.list();
        List<UnitItEntity> unitItList = unitItService.list();
        List<UnitKeywordEntity> keywordList = unitKeywordService.list();

        // 调用 export() 方法导出数据到不同文件
        export(DConstant.AD_CREATIVE, creativeList);
        export(DConstant.AD_CREATIVE_UNIT, creativeUnitList);
        export(DConstant.AD_PLAN, planList);
        export(DConstant.AD_UNIT, unitList);
        export(DConstant.AD_UNIT_DISTRICT, districtList);
        export(DConstant.AD_UNIT_IT, unitItList);
        export(DConstant.AD_UNIT_KEYWORD, keywordList);
    }

    private void export(String filePath, List<?> dataList) {
        // 创建 Gson 对象
        Gson gson = new GsonBuilder().setPrettyPrinting().create();

        try (FileWriter writer = new FileWriter(DConstant.DATA_ROOT_DIR + filePath)) {
            // 将数据列表转换为 JSON 字符串并写入文件
            gson.toJson(dataList, writer);
            System.out.println("JSON 数据导出成功到文件：" + filePath);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("导出 JSON 数据时出现异常：" + e.getMessage());
        }
    }


}
